package com.xying.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xying.common.Const;
import com.xying.common.ResponseCode;
import com.xying.common.ServerResponse;
import com.xying.dao.UsrMapper;
import com.xying.pojo.Usr;
import com.xying.service.UsrService;
import com.xying.util.MD5Util;
import com.xying.util.ValidateUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 * @author Hisen
 * @date 2017/11/8
 */
@Service
public class UsrServiceImpl implements UsrService{

  @Autowired
  private UsrMapper usrMapper;

  @Override
  public ServerResponse login(String username, String password) {
    ServerResponse serverResponse = ValidateUtil.validate(username, password);
    if (!serverResponse.isSuccess()) {
      return serverResponse;
    }

    Usr usr = usrMapper.selectUsrByUserNamePassword(username, MD5Util.MD5EncodeUTF8(password));
    if(usr == null) {
      return ServerResponse.createByErrorMessage("账号密码错误");
    }

    usr.setPassword(StringUtils.EMPTY);
    return ServerResponse.createBySuccess(usr);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse register(Usr usr) {
    usr.setIdNo(UUID.randomUUID().toString().replace("-", ""));
    usr.setPassword(MD5Util.MD5EncodeUTF8(usr.getPassword()));
    usr.setCreateTime(new Date());
    usr.setUpdateTime(new Date());
    usr.setRoleId(Const.ROLE.NORMAL_USR.getCode());
    usr.setStatus(true);
    int resultCount = usrMapper.insert(usr);
    if(resultCount <= 0){
      return ServerResponse.createByErrorMessage("创建用户失败");
    }
    return ServerResponse.createBySuccess();
  }

  @Override
  public ServerResponse getPersonalInfo(Usr usr) {
    if(usr == null){
      return ServerResponse.createByErrorMessage("请上传正确用户信息");
    }
    return ServerResponse.createBySuccess(usr);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse savePersonalInfo(Usr usr) {

    Usr user = new Usr();
    user.setIdNo(usr.getIdNo());
    user.setDepartment(usr.getDepartment());
    user.setSex(usr.getSex());
    user.setRoleId(usr.getRoleId());
    user.setUpdateTime(new Date());
    int rowCount = usrMapper.updateByPrimaryKeySelective(user);
    if(rowCount <= 0){
      return ServerResponse.createByErrorMessage("更新用户信息失败");
    }

    return ServerResponse.createBySuccess(usr);
  }

  @Override
  public ServerResponse updatePassword(String idNo, String oldPassword, String newPassword) {
    ServerResponse serverResponse = ValidateUtil.validate(idNo, oldPassword, newPassword);
    if(!serverResponse.isSuccess()) {
      return serverResponse;
    }

    //MD5盐值加密
    String password = MD5Util.MD5EncodeUTF8(oldPassword);
    int rowCount = usrMapper.selectCountByIdNoPassword(idNo, password);
    if(rowCount <= 0){
      return ServerResponse.createByErrorMessage("验证旧密码错误");
    }

    Usr usr = new Usr();
    usr.setIdNo(idNo);
    usr.setPassword(MD5Util.MD5EncodeUTF8(newPassword));
    rowCount = usrMapper.updateByPrimaryKeySelective(usr);
    if(rowCount <= 0){
      return ServerResponse.createByErrorMessage("修改密码失败");
    }

    return ServerResponse.createBySuccess();
  }



  //backend


  @Override
  public ServerResponse adminLogin(String username, String password) {
    ServerResponse serverResponse = ValidateUtil.validate(username, password);
    if (!serverResponse.isSuccess()) {
      return serverResponse;
    }

    password = MD5Util.MD5EncodeUTF8(password);
    Usr usr = usrMapper.selectUsrByUserNamePassword(username, password);
    if(usr == null){
      return ServerResponse.createByErrorMessage("账号密码错误");
    }
    if(usr.getRoleId() < Const.ROLE.ADMIN_USR.getCode()){
      return ServerResponse.createByErrorMessage("用户没有权限");
    }

    usr.setPassword(StringUtils.EMPTY);
    return ServerResponse.createBySuccess(usr);
  }

  @Override
  public ServerResponse<Usr> checkAdmin(Usr usr) {
    Integer rowCount = usrMapper.selectUsrByUserNameAndAdminRole(usr.getUserName(), Const.ROLE.ADMIN_USR.getCode());
    if(rowCount <= 0) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.PERMISSION_DENIED.getCode(), ResponseCode.PERMISSION_DENIED.getDesc());
    }
    return ServerResponse.createBySuccess();
  }

  @Override
  public ServerResponse listAllUsr(Integer pageNum, Integer pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    List<Usr> usrList = usrMapper.listAllUsr();
    if (CollectionUtils.isEmpty(usrList)) {
      return ServerResponse.createByErrorMessage("查找失败");
    }

    PageInfo pageInfo = new PageInfo(usrList);
    return ServerResponse.createBySuccess(pageInfo);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public ServerResponse updateUsrInfo(Usr user) {
    if(user == null) {
      return ServerResponse.createByErrorMessage("必要信息不能为空");
    }

    user.setUpdateTime(new Date());
    if(user.getIdNo() != null){
      //校验用户名是否重复
      int rowCount = usrMapper.selectCountByUserName(user.getUserName(), user.getIdNo());
      if (rowCount > 0) {
        return ServerResponse.createByErrorMessage("用户以及存在");
      }

      if (!StringUtils.isEmpty(user.getPassword())) {
        user.setPassword(MD5Util.MD5EncodeUTF8(user.getPassword()));
      }
      int rewCount = usrMapper.updateByPrimaryKeySelective(user);
      if(rewCount <= 0) {
        return ServerResponse.createByErrorMessage("更新信息失败");
      }
      return ServerResponse.createBySuccess();
    }else{
      user.setPassword(MD5Util.MD5EncodeUTF8(user.getPassword()));
      user.setCreateTime(new Date());
      user.setIdNo(UUID.randomUUID().toString().replace("-", ""));
      //校验用户名是否重复
      int rowCount = usrMapper.selectCountByUserName(user.getUserName(), user.getIdNo());
      if (rowCount > 0) {
        return ServerResponse.createByErrorMessage("用户名重复");
      }

      rowCount = usrMapper.insert(user);
      if(rowCount <= 0) {
        return ServerResponse.createByErrorMessage("用户更新失败");
      }
      return ServerResponse.createBySuccess();
    }
  }

  @Override
  public ServerResponse deleteUser(String idNo) {
    ServerResponse serverResponse = ValidateUtil.validate(idNo);
    if (!serverResponse.isSuccess()) {
      return serverResponse;
    }

    //todo 删除用户信息
    //serverResponse = commonService.deleteUser(idNo);
    return serverResponse;
  }

  @Override
  public ServerResponse searchUserName(String userName, Integer pageNum, Integer pageSize) {
    ServerResponse serverResponse = ValidateUtil.validate(userName);
    if (!serverResponse.isSuccess()) {
      return serverResponse;
    }

    userName = "%" + userName + "%";
    PageHelper.startPage(pageNum, pageSize);
    List UsrList = usrMapper.listByUserName(userName);
    if (CollectionUtils.isEmpty(UsrList)) {
      return ServerResponse.createByErrorMessage("查找用户失败");
    }
    PageInfo pageInfo = new PageInfo(UsrList);
    return ServerResponse.createBySuccess(pageInfo);
  }

  @Override
  public ServerResponse loginMD5(String userName, String password) {
    ServerResponse serverResponse = ValidateUtil.validate(userName, password);
    if (!serverResponse.isSuccess()) {
      return serverResponse;
    }

    Usr usr = usrMapper.selectUsrByUserNamePassword(userName, password);
    if(usr == null) {
      return ServerResponse.createByErrorMessage("登录失败");
    }

    usr.setPassword(StringUtils.EMPTY);
    return ServerResponse.createBySuccess(usr);
  }

  @Override
  public ServerResponse checkUsername(String username) {
    List userList = usrMapper.listByUserName(username);
    if (userList.size() > 0) {
      return ServerResponse.createByErrorMessage("用户名已存在");
    }

    return ServerResponse.createBySuccess();
  }
}
